from flask import Flask, jsonify, request
from flasgger import Swagger, swag_from

app = Flask(__name__)

# 配置Swagger
app.config['SWAGGER'] = {
    'title': '用户管理API',
    'description': '使用flasgger自动生成的API文档',
    'version': '1.0.0',
    'termsOfService': 'https://example.com/terms',
    'uiversion': 3  # 使用Swagger UI v3
}

# 初始化Swagger
swagger = Swagger(app)

# 模拟数据库
users = [
    {'id': 1, 'name': '张三', 'email': 'zhangsan@example.com'},
    {'id': 2, 'name': '李四', 'email': 'lisi@example.com'}
]
next_id = 3

@app.route('/users', methods=['GET'])
def get_users():
    """
    获取所有用户列表
    ---
    tags:
      - 用户管理
    responses:
      200:
        description: 成功返回用户列表
        schema:
          type: array
          items:
            type: object
            properties:
              id:
                type: integer
                example: 1
              name:
                type: string
                example: 张三
              email:
                type: string
                example: zhangsan@example.com
    """
    return jsonify(users)

@app.route('/users', methods=['POST'])
def create_user():
    """
    创建新用户
    ---
    tags:
      - 用户管理
    parameters:
      - name: body
        in: body
        required: true
        schema:
          type: object
          required:
            - name
            - email
          properties:
            name:
              type: string
              example: 王五
            email:
              type: string
              example: wangwu@example.com
    responses:
      201:
        description: 用户创建成功
    """
    global next_id
    user = request.json
    user['id'] = next_id
    next_id += 1
    users.append(user)
    return jsonify(user), 201

@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """
    根据ID获取用户信息
    ---
    tags:
      - 用户管理
    parameters:
      - name: user_id
        in: path
        type: integer
        required: true
        description: 用户ID
        example: 1
    responses:
      200:
        description: 成功返回用户信息
      404:
        description: 用户不存在
    """
    for user in users:
        if user['id'] == user_id:
            return jsonify(user)
    return jsonify({"error": "用户不存在"}), 404

# 也可以将文档写在外部YAML文件中，通过swag_from引用
@app.route('/users/<int:user_id>', methods=['DELETE'])
@swag_from('delete_user.yaml')  # 外部文档文件
def delete_user(user_id):
    global users
    for index, user in enumerate(users):
        if user['id'] == user_id:
            users.pop(index)
            return jsonify({"message": "用户已删除"}), 200
    return jsonify({"error": "用户不存在"}), 404

if __name__ == '__main__':
    app.run(debug=True)
